<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>01 - 加载百度离线地图-EPSG:3857</title>
    <script src="../lib/ol6.4.3/ol.js"></script>
    <script type="text/javascript" src="http://www.megomap.com/ol/bd09.js" charset="utf-8"></script>
    <link rel="stylesheet" href="../css/ol6.4.3/ol.css">
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html, body {
            width: 100%;
            height: 100%;
        }

        #map {
            width: auto;
            height: 100%;
        }
    </style>
</head>
<body>
<div id="map"></div>
</body>
<script>
    const projection = ol.proj.get('EPSG:3857');
    const projectionExtent = projection.getExtent();

    const resolutions = [];
    const maxZoom = 18;
    // 计算百度使用的分辨率
    for (let i = 0; i <= maxZoom; ++i) {
        resolutions[i] = Math.pow(2, maxZoom - i);
    }

    const tileGrid = new ol.tilegrid.TileGrid({
        origin: [0, 0],
        resolutions: resolutions,
        extent: projectionExtent
    });

    const baiduSource = new ol.source.TileImage({
        projection: 'EPSG:3857',
        tileGrid: tileGrid,
        tileUrlFunction: (tileCoord, pixelRatio, proj) => {
            let [z, x, y] = tileCoord;
            // 百度瓦片服务url将负数使用M前缀来标识
            return `http://192.168.130.38:8080/baidumaps/roadmap/${z}/${x}/${-y}.png`;
            // return `http://192.168.106.167:8080/scgis/pic?level=${z}&col=${x}&row=${-y}`;
        }
    });
    // 百度地图层
    const baiduMapLayer = new ol.layer.Tile({
        source: baiduSource
    });

    const circlePoint = ol.proj.transform([116.384722, 39.889916], 'EPSG:4326', 'EPSG:3857');

    const iconFeature = new ol.Feature({
        // [110.23455490789895, 20.03350339866073],ol.proj.fromLonLat([109.88388,19.20959])
        geometry: new ol.geom.Point(ol.proj.fromLonLat([116.384722, 39.889916]))
    });

    const iconStyle = new ol.style.Style({
        image: new ol.style.Icon(
            /** @type {olx.style.IconOptions} */ ({
                anchor: [10, 26],
                anchorXUnits: 'pixels',
                anchorYUnits: 'pixels',
                src: '../image/position_orange.png'
            })
        )
    });

    iconFeature.setStyle(iconStyle);

    const vectorSource = new ol.source.Vector({
        features: [iconFeature],
    });

    const iconLayer = new ol.layer.Vector({
        source: vectorSource,
    });

    const map = new ol.Map({
        layers: [
            baiduMapLayer,
            iconLayer
        ],
        target: 'map',
        view: new ol.View({
            center: ol.proj.transform([116.384722, 39.889916], 'EPSG:4326', 'EPSG:3857'),
            // center: [0, 0],
            projection: 'EPSG:3857',
            zoom: 4,
            maxZoom: 10,
            minZoom: 1
        })
    });
</script>
</html>